package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.AboutUs;
import com.antdesignbackend.backend.entity.Shop;
import com.antdesignbackend.backend.service.AboutUsService;
import com.antdesignbackend.backend.service.IShopService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/aboutus")
public class AboutUsController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Integer id;

    @Autowired
    AboutUsService aboutUsService;
    @Autowired
    private IShopService shopService;

    @GetMapping("/index")
    @AuthToken
    public String index(){
        return "aboutus/index";
    }

    //门店介绍
    @GetMapping("/editing/{id}")
    @AuthToken
    public String editing(@PathVariable int id){
        this.id=id;
        return "aboutus/editing";
    }
    //周边配套
    @GetMapping("/editingzb/{id}")
    @AuthToken
    public String editingzb(@PathVariable int id){
        this.id=id;
        return "aboutus/editingzb";
    }
    //预定须知
    @GetMapping("/editingyd/{id}")
    @AuthToken
    public String editingyd(@PathVariable int id){
        this.id=id;
        return "aboutus/editingyd";
    }


    /**
     * 查询富文本的内容
     * @return
     */
    @AuthToken
    @GetMapping("/show")
    @ResponseBody
    public AboutUs show(){
        AboutUs aboutUs = new AboutUs();
        try {
            aboutUs = aboutUsService.getById(1);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return aboutUs;
    }

    /**
     * 保存富文本的内容
     * @param aboutUs
     * @return
     */
    @AuthToken
    @PostMapping("/save")
    @ResponseBody
    public ReturnVO save(@RequestBody AboutUs aboutUs) {
        try {
            aboutUsService.saveOrUpdate(aboutUs);
            return new ReturnVO();
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }
    /**
     * 查询门店介绍
     * @return
     */
    @AuthToken
    @GetMapping("/mdshow")
    @ResponseBody
    public AboutUs mdshow(){
        AboutUs aboutUs = new AboutUs();
        try {
            Shop shop = shopService.getById(id);
            aboutUs.setContent(shop.getSynopsis());
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return aboutUs;
    }
    /**
     * 门店介绍
     * @param aboutUs
     * @return
     */
    @PostMapping("/mdsave")
    @ResponseBody
    public ReturnVO mdsave(@RequestBody AboutUs aboutUs) {
        try {
            String content=aboutUs.getContent();
            List<String> pics=getImgSrc(content);
            for(int i=0;i<pics.size();i++){
                if(pics.get(i).contains("data:image/jpeg;base64,")){
                    String pic=pics.get(i).replace("data:image/jpeg;base64,","");
                    String imageSrc="C:/WebApp/MVC.UI/WeUI/disk2/example/images/";
                    String imageName=getCode()+".jpg";
                    GenerateImage(pic,imageSrc+imageName);
                    content=content.replace(pics.get(i),"http://www.3y-space.com:18082/images/"+imageName);
                }
            }
            Shop shop=shopService.getById(id);
            shop.setSynopsis(content);
            shopService.updateById(shop);
            return new ReturnVO();
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }
    /**
     * 查询周边配套
     * @return
     */
    @AuthToken
    @GetMapping("/zbshow")
    @ResponseBody
    public AboutUs zbshow(){
        AboutUs aboutUs = new AboutUs();
        try {
            Shop shop = shopService.getById(id);
            aboutUs.setContent(shop.getPeriphery());
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return aboutUs;
    }
    /**
     * 周边配套
     * @param aboutUs
     * @return
     */
    @PostMapping("/zbsave")
    @ResponseBody
    public ReturnVO zbsave(@RequestBody AboutUs aboutUs) {
        try {
            String content=aboutUs.getContent();
            List<String> pics=getImgSrc(content);
            for(int i=0;i<pics.size();i++){
                if(pics.get(i).contains("data:image/jpeg;base64,")){
                    String pic=pics.get(i).replace("data:image/jpeg;base64,","");
                    String imageSrc="C:/WebApp/MVC.UI/WeUI/disk2/example/images/";
                    String imageName=getCode()+".jpg";
                    GenerateImage(pic,imageSrc+imageName);
                    content=content.replace(pics.get(i),"http://www.3y-space.com:18082/images/"+imageName);
                }
            }
            Shop shop=shopService.getById(id);
            shop.setPeriphery(content);
            shopService.updateById(shop);
            return new ReturnVO();
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }
    /**
     * 查询预订须知
     * @return
     */
    @AuthToken
    @GetMapping("/ydshow")
    @ResponseBody
    public AboutUs ydshow(){
        AboutUs aboutUs = new AboutUs();
        try {
            Shop shop = shopService.getById(id);
            aboutUs.setContent(shop.getReservation());
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return aboutUs;
    }
    /**
     * 预订须知
     * @param aboutUs
     * @return
     */
    @PostMapping("/ydsave")
    @ResponseBody
    public ReturnVO ydsave(@RequestBody AboutUs aboutUs) {
        try {
            String content=aboutUs.getContent();
            List<String> pics=getImgSrc(content);
            for(int i=0;i<pics.size();i++){
                if(pics.get(i).contains("data:image/jpeg;base64,")){
                    String pic=pics.get(i).replace("data:image/jpeg;base64,","");
                    String imageSrc="C:/WebApp/MVC.UI/WeUI/disk2/example/images/";
                    String imageName=getCode()+".jpg";
                    GenerateImage(pic,imageSrc+imageName);
                    content=content.replace(pics.get(i),"http://www.3y-space.com:18082/images/"+imageName);
                }
            }
            Shop shop=shopService.getById(id);
            shop.setReservation(content);
            shopService.updateById(shop);
            return new ReturnVO();
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnVO(ReturnCode.FAIL);
        }
    }
    public String getCode(){
        long random1 = System.currentTimeMillis();
        Random random2 = new Random();
        int rd = random2.nextInt(9);
        String dateKey =  random1 + "" + rd;
        return dateKey;
    }

    public static boolean GenerateImage(String base64str, String savePath) {
        //对字节数组字符串进行Base64解码并生成图片
        if (base64str == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(base64str);
            for (int i = 0; i < b.length; ++i) {
                //调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            OutputStream out = new FileOutputStream(savePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public static List<String> getImgSrc(String htmlStr) {
        if( htmlStr == null ){
            return null;
        }
        String img = "";
        Pattern p_image;
        Matcher m_image;
        List<String> pics = new ArrayList<String>();
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            img = img + "," + m_image.group();
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }



}

